package com.erp.framework.util;


import com.erp.framework.constant.ShiroConstants;
import com.erp.framework.util.uuid.UUID;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @Author cj
 * @Date 2020/8/10 14:32
 */
public class AutoFillUtils {

    public static void setCreateInfo(Object obj) {
        setCreateInfo(obj, defaultUser());
    }

    public static void setCreateInfo(Object obj, String userName) {

        try {
            Class<?> clazz = obj.getClass();
            Method setUUID = clazz.getMethod("setId", String.class);
            Method setCreateBy = clazz.getMethod("setCreateBy", String.class);
            Method setCreateTime = clazz.getMethod("setCreateTime", Date.class);
            setUUID.invoke(obj, UUID.randomUUID().toString().replace("-", "").toUpperCase());
            setCreateBy.invoke(obj, userName);
            setCreateTime.invoke(obj, new Date());
        } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    public static void setEditInfo(Object obj) {
        setEditInfo(obj, defaultUser());
    }

    public static void setEditInfo(Object obj, String userName) {

        try {
            Class<?> clazz = obj.getClass();
            Method setUpdateBy = clazz.getMethod("setUpdateBy", String.class);
            Method setUpdateTime = clazz.getMethod("setUpdateTime", Date.class);
            setUpdateBy.invoke(obj, userName);
            setUpdateTime.invoke(obj, new Date());
        } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }


    private static String defaultUser() {
        try {
            String userName = ShiroUtils.getUserName();
            if (StringUtils.isNotBlank(userName)) {
                return userName;
            }
        } catch (Exception ignored) {
        }
        try {
            Object obj = CacheUtils.get(ShiroConstants.CURRENT_USERNAME);

            if (obj != null) {
                return String.valueOf(obj);
            }
        } catch (Exception ignored) {
        }

        return "unknown";
    }


}
